package cn.neusoft.controller;

import cn.neusoft.domain.*;
import cn.neusoft.exception.AppException;
import cn.neusoft.exception.AppExceptionCodeMsg;
import cn.neusoft.query.OrderQuery;
import cn.neusoft.service.OrderService;
import cn.neusoft.util.EnumUtils;
import cn.neusoft.util.UUIDUtils;
import cn.neusoft.vo.PageBean;
import cn.neusoft.vo.ResultBean;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController // @Controller + @ResponseBody
@RequestMapping(value = "/order", produces = "application/json;charset=utf-8")
//接口文档的注解
@Api(value = "客户模块的API", description = "订单相关功能")
public class OrderController {
    @Autowired
    OrderService orderService;


    @GetMapping("/all")
    public ResultBean findAll(){
        List<Order> orders = orderService.findAll();
        return ResultBean.success(orders);
    }
    @PostMapping("/amount/{commodity_id}") //   Post + /order/amount/{#id}
    @ApiOperation(value = "查询库存量")
    public ResultBean findOccupiedAmount(@PathVariable("commodity_id") String commodity_id) {
        if (commodity_id == null) {
            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
        }

        Long warehouseamount = orderService.findTrueAmount(commodity_id)-orderService.findOccupiedAmount(commodity_id);
        return ResultBean.success(warehouseamount);
    }

    @PutMapping("/judgeamount")//   Put + /order/judgeamount
    @ApiOperation(value = "根据库存判断订单状态")
    public ResultBean judgeNormalAmount(@RequestBody Order order) {
        if (order == null) {
            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
        }
        Long warehouseaccount = orderService.findOccupiedAmount(order.getOrder_commodity_id());
        Long orderaccount;
        Long trueaccount = orderService.findTrueAmount(order.getOrder_commodity_id());
        if (order.getOrder_kind() == 1) {
            orderaccount = orderService.findNormalOrderAmount(order.getOrder_id());
            if (trueaccount-warehouseaccount < orderaccount) {
                order.setOrder_status("0");
                orderService.judgeAmount(order);
                return ResultBean.success("0");
            } else {
                order.setOrder_status("1");
                orderService.judgeAmount(order);
                Long occupided=warehouseaccount+orderaccount;
                orderService.updateoccupamount(order.getOrder_commodity_id(),occupided);
                return ResultBean.success("1");
            }
        } else if (order.getOrder_kind() == 3) {
            orderaccount = orderService.findExchangeOrderAmount(order.getOrder_id());
            if (trueaccount-warehouseaccount < orderaccount) {
                order.setOrder_status("0");
                orderService.judgeAmount(order);
                return ResultBean.success("0");
            } else {
                order.setOrder_status("1");
                orderService.judgeAmount(order);
                Long occupided=warehouseaccount+orderaccount;
                orderService.updateoccupamount(order.getOrder_commodity_id(),occupided);
                return ResultBean.success("1");
            }

        }
        return ResultBean.success("1");
    }

    @PostMapping("/order_normal") //   Post + /customer/order_normal
    @ApiOperation(value = "新增正常订单")
    public ResultBean addOrder(@RequestBody Map<String, Object> map) {
        // 将返回结果转为字符串
        String jsonStr = JSON.toJSONString(map.get("order"));
        // 将json字符串转为Order对象
        Order order = JSON.parseObject(jsonStr, Order.class);

        // 将返回结果转为字符串
        String jsonStr2 = JSON.toJSONString(map.get("order_normal"));
        // 将json字符串转为Order_normal对象
        Order_normal order_normal = JSON.parseObject(jsonStr2, Order_normal.class);

        // 将返回结果转为字符串
        String jsonStr3 = JSON.toJSONString(map.get("operator_id"));
        // 将json字符串转为操作者id
        String operator_id = JSON.parseObject(jsonStr3, String.class);

        // 将返回结果转为字符串
        String jsonStr4 = JSON.toJSONString(map.get("order_customer_id"));
        // 将json字符串转为客户id
        String customer_id = JSON.parseObject(jsonStr4, String.class);
        //判断子订单正常订单是否为空  为空则抛出异常
        if (order_normal == null) {
            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
        }
        //设置uuid
        String order_id = UUIDUtils.getUUID();
        order_normal.setOrder_id(order_id);
        order.setOrder_id(order_id);
        //设置订单种类
        order.setOrder_kind(1);
        //设置订单客户
        order.setOrder_customer_id(customer_id);
        //设置创建人
        order.setCreate_by(operator_id);
        //设置创建时间
        Date create_time = new Date();
        order.setCreate_time(create_time);
        orderService.addOrder(order);
        orderService.addOrder_normal(order_normal);
        return ResultBean.success(order_id);
    }

    @PutMapping("/cancelorder")//   Put + /order/judgeamount
    @ApiOperation(value = "退订")
    public ResultBean cancelOrder(@RequestBody Order order) {
        if (order == null) {
            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
        }
        if (Objects.equals(order.getOrder_status(), "1")) {
            Long warehouseaccount = orderService.findOccupiedAmount(order.getOrder_commodity_id());//已占用库存
            Long orderaccount=orderService.findNormalOrderAmount(order.getOrder_id());//订单需求货物数量
            Long occupied=warehouseaccount-orderaccount;
            orderService.updateoccupamount(order.getOrder_commodity_id(),occupied);
            order.setOrder_status("4");
            orderService.judgeAmount(order);
        } else if(Objects.equals(order.getOrder_status(), "0")){
            order.setOrder_status("4");
            orderService.judgeAmount(order);
        }else if (Objects.equals(order.getOrder_status(), "2")) {
            return ResultBean.cantcancel("订单已经调拨，无法退订");
        }
        return ResultBean.success();
    }

    @PostMapping("/order_exchange") //   Post + /customer/order_exchange
    @ApiOperation(value = "新增换货订单")
    public ResultBean addExchangeOrder(@RequestBody Map<String, Object> map) {
        // 将返回结果转为字符串
        String jsonStr = JSON.toJSONString(map.get("order"));
        // 将json字符串转为Order对象
        Order order = JSON.parseObject(jsonStr, Order.class);

        // 将返回结果转为字符串
        String jsonStr2 = JSON.toJSONString(map.get("order_exchange"));
        // 将json字符串转为Order_exchange对象
        Order_exchange order_exchange = JSON.parseObject(jsonStr2, Order_exchange.class);

        // 将返回结果转为字符串
        String jsonStr3 = JSON.toJSONString(map.get("operator_id"));
        // 将json字符串转为操作者id
        String operator_id = JSON.parseObject(jsonStr3, String.class);

        // 将返回结果转为字符串
        String jsonStr4 = JSON.toJSONString(map.get("customer_id"));
        // 将json字符串转为客户id
        String customer_id = JSON.parseObject(jsonStr4, String.class);
        //判断子订单换货订单是否为空  为空则抛出异常
        if (order_exchange == null) {
            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
        }
        //设置uuid
        String order_id = UUIDUtils.getUUID();
        order_exchange.setOrder_id(order_id);
        order.setOrder_id(order_id);
        //设置订单种类
        order.setOrder_kind(3);
        //设置订单客户
        order.setOrder_customer_id(customer_id);
        //设置创建人
        order.setCreate_by(operator_id);

        //设置创建时间
        Date create_time = new Date(System.currentTimeMillis());
        order.setCreate_time(create_time);

        orderService.addOrder(order);
        orderService.addOrder_exchange(order_exchange);
        return ResultBean.success(order_id);
    }

    @PostMapping("/order_return") //   Post + /customer/order_return
    @ApiOperation(value = "新增退货订单")
    public ResultBean addReturnOrder(@RequestBody Map<String, Object> map) {
        // 将返回结果转为字符串
        String jsonStr = JSON.toJSONString(map.get("order"));
        // 将json字符串转为Order对象
        Order order = JSON.parseObject(jsonStr, Order.class);

        // 将返回结果转为字符串
        String jsonStr2 = JSON.toJSONString(map.get("order_return"));
        // 将json字符串转为Order_exchange对象
        Order_return order_return = JSON.parseObject(jsonStr2, Order_return.class);

        // 将返回结果转为字符串
        String jsonStr3 = JSON.toJSONString(map.get("operator_id"));
        // 将json字符串转为操作者id
        String operator_id = JSON.parseObject(jsonStr3, String.class);

        // 将返回结果转为字符串
        String jsonStr4 = JSON.toJSONString(map.get("customer_id"));
        // 将json字符串转为客户id
        String customer_id = JSON.parseObject(jsonStr4, String.class);
        //判断子订单换货订单是否为空  为空则抛出异常
        if (order_return == null) {
            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
        }
        //设置uuid
        String order_id = UUIDUtils.getUUID();
        order_return.setOrder_id(order_id);
        order.setOrder_id(order_id);
        //设置订单种类
        order.setOrder_kind(2);
        //设置订单客户
        order.setOrder_customer_id(customer_id);
        //设置创建人
        order.setCreate_by(operator_id);
        //设置订单状态为可分配
        order.setOrder_status("1");
        //设置创建时间

        Date create_time = new Date(System.currentTimeMillis());
        order.setCreate_time(create_time);
        orderService.addOrder(order);
        orderService.addOrder_return(order_return);
        return ResultBean.success(order_id);
    }

    @PostMapping("/pagecusorder")  //  Post + /order/pagecusorder
    @ApiOperation(value = "分页查询客户下属订单信息")
    public ResultBean findCustoOrderByPage(@RequestBody OrderQuery baseQuery) {
        PageBean<Order> pageBean = orderService.findCustoOrderByPage(baseQuery);
        return ResultBean.success(pageBean);
    }

    @PostMapping("/orderDetail")  //  Post + /order/pagecusorder
    @ApiOperation(value = "查询订单详细信息")
    public ResultBean orderDetail(@RequestBody Order order) {
        Order order1 = new Order();
        if (order.getOrder_kind() == 1) {
            order1 = orderService.findNormalOrder(order);
        } else if (order.getOrder_kind() == 2) {
            order1 = orderService.findReturnOrder(order);
        } else if (order.getOrder_kind() == 3) {
            order1 = orderService.findExchangeOrder(order);
        }
        return ResultBean.success(order1);
    }

    @PostMapping("/page")
    @ApiOperation(value = "分页模糊查询订单信息")
    public ResultBean findByPage(@RequestBody OrderQuery orderQuery) {
        final List<Integer> order_kinds = Arrays.asList(1,2,3);

        if (orderQuery == null
                || StringUtils.isEmpty(orderQuery.getPageSize())
                || StringUtils.isEmpty(orderQuery.getPageNow())
                || orderQuery.getOrder_kind() == null
        ) {
            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
        }


        Integer order_kind = orderQuery.getOrder_kind();

        // 订单类型非法
        if(!order_kinds.contains(order_kind)){
            throw new AppException(AppExceptionCodeMsg.ORDER_KIND_INVALID);
        }

        PageBean pageBean = null;

        // 查正常订单
        if(Objects.equals(order_kind, 1)){
             pageBean = orderService.findNormalOrderByPage(orderQuery);
        }

        // 查退货单
        if(Objects.equals(order_kind, 2)){
            pageBean = orderService.findReturnOrderByPage(orderQuery);
        }

        // 查换货单
        if(Objects.equals(order_kind, 3)){
            pageBean = orderService.findExchangeOrderByPage(orderQuery);
        }

        return ResultBean.success(pageBean);
    }

    @PostMapping("/findByCondition")
    @ApiOperation(value = "查询订单信息")
    public ResultBean<Order1> findOrderByCondition(@RequestBody OrderQuery orderQuery) {
        final List<Integer> order_kinds = Arrays.asList(1,2,3);
        if (orderQuery == null
                || StringUtils.isEmpty(orderQuery.getOrder_id())
                || StringUtils.isEmpty(orderQuery.getOrder_kind())
        ) {
            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
        }

        Integer order_kind = orderQuery.getOrder_kind();


        // 订单类型非法
        if(!order_kinds.contains(order_kind)){
            throw new AppException(AppExceptionCodeMsg.ORDER_KIND_INVALID);
        }

        Order1 resultOrder = new Order1();

        // 查正常订单
        if(Objects.equals(order_kind, 1)){
            resultOrder = orderService.findOrderNormalByCondition(orderQuery);
        }

        // 查退货单
        if(Objects.equals(order_kind, 2)){
            resultOrder = orderService.findOrderReturnByCondition(orderQuery);
        }

        // 查换货单
        if(Objects.equals(order_kind, 3)){
            resultOrder = orderService.findOrderExchangeByCondition(orderQuery);
        }

        return ResultBean.success(resultOrder);
    }

    @PutMapping("/updateStatus")
    @ApiOperation(value = "修改订单状态")
    public ResultBean updateOrderStatus(@RequestBody Order1 order) {

        if (order == null
                || StringUtils.isEmpty(order.getOrder_id())
                || StringUtils.isEmpty(order.getOrder_status())) {

            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
        }

        orderService.updateOrderStatus(order);

        return ResultBean.success();
    }

    @PutMapping("/updateRestock")
    public ResultBean updateOrderRestock(@RequestBody Order order){
        if (order == null
                || StringUtils.isEmpty(order.getOrder_id())
                || StringUtils.isEmpty(order.getIf_restock())) {

            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
        }

        orderService.updateOrderRestock(order);

        return ResultBean.success();
    }

    /**
     * 新的分页查询接口，原来的那个已经连通前端了，就没改
     * 这个是为了方便服务间通信搞得新接口，调度中心用的就是这个接口
     * 麻了
     * @param orderQuery
     * @return
     */
    @PostMapping("/page2")
    @ApiOperation(value = "分页模糊查询订单信息2")
    public ResultBean findOrderByPage(@RequestBody OrderQuery orderQuery) {
        if (orderQuery == null
                || StringUtils.isEmpty(orderQuery.getPageSize())
                || StringUtils.isEmpty(orderQuery.getPageNow())
                || orderQuery.getOrder_kind() == null
        ) {
            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
        }

        PageBean<Order1> pageBean = orderService.findOrderByPage(orderQuery);

        return ResultBean.success(pageBean);
    }

    @PutMapping("/status")
    public void updateOrderStatusWhenCreate(@RequestBody Order order) {
        orderService.updateOrderStatusWhenCreate(order);
    }

    @GetMapping("/countMatchingOrders/{commodity_id}")
    public int countMatchingOrders(@PathVariable String commodity_id){
       return(orderService.countMatchingOrders(commodity_id));
    }
}
